<template>
  <div class="user-management-container">
    <h1 style="color: #3998a9;">用户管理</h1>
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input v-model="searchParams.username" placeholder="请输入用户名" clearable class="search-input"
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon>
            <Avatar />
          </el-icon>
        </template>
      </el-input>
      <el-input v-model="searchParams.nickname" placeholder="请输入昵称" clearable class="search-input"
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon>
            <User />
          </el-icon>
        </template>
      </el-input>
      <el-input v-model="searchParams.phone" placeholder="请输入手机号" clearable class="search-input"
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon>
            <Iphone />
          </el-icon>
        </template>
      </el-input>

      <el-input v-model="searchParams.email" placeholder="请输入邮箱" clearable class="search-input"
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon>
            <Message />
          </el-icon>
        </template>
      </el-input>
      <el-select v-model="searchParams.roleIds" placeholder="请选择角色" clearable class="search-input"
        @change="handleSearch">
        <el-option v-for="role in userStore.rolesList" :key="role.roleId" :label="role.rolename" :value="role.roleId" />
      </el-select>

      <el-select v-model="searchParams.isActive" placeholder="请选择状态" clearable class="search-input"
        @change="handleSearch">
        <el-option label="全部" value="null" />
        <el-option label="已激活" value="true" />
        <el-option label="未激活" value="false" />
      </el-select>

      <el-button type="primary" @click="handleSearch" :icon="Search" class="search-btn">
        查询
      </el-button>
      <el-button @click="resetSearch" :icon="Refresh" class="reset-btn">
        重置
      </el-button>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-area">
      <el-button type="primary" @click="showAddDrawer" :icon="Plus" class="add-btn">
        添加用户
      </el-button>
    </div>

    <!-- 用户表格 -->
    <div class="table-area">
      <el-table :data="userStore.users" border stripe style="width: 100%" height="calc(100vh - 220px)"
        v-loading="userStore.loading">
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" v-if="row.avatar" />
            <el-avatar v-else icon="User" />
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="150" sortable />
        <el-table-column prop="nickname" label="昵称" width="150" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="roles" label="角色" width="150">
          <template #default="{ row }">
            <div v-if="row.roles && row.roles.length > 0">
              <el-tag v-for="role in row.roles" :key="role.roleId" :type="getRoleTagType(role.roleName)" effect="light">
                {{ role.roleName }} <!-- 显示角色名称 -->
                <!-- 注意这里是登录所传入的角色名称 -->

              </el-tag>
            </div>
            <el-button v-else type="default" disabled size="small" plain>暂无</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="状态" width="120">
          <template #default="{ row }">
            <el-button size="small" :type="row.isActive ? 'success' : 'info'" plain @click="toggleStatus(row)">
              {{ row.isActive ? '已激活' : '未激活' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" plain @click="handleEdit(row)" :icon="Edit">
              编辑
            </el-button>
            <el-button size="small" type="danger" plain @click="handleDelete(row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination v-model:current-page="userStore.page" v-model:page-size="userStore.pageSize"
        :page-sizes="[10, 20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
        :total="userStore.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 添加/编辑用户抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" :direction="'rtl'" size="40%" destroy-on-close>
      <el-form ref="userFormRef" :model="currentUser" :rules="userRules" label-width="100px" label-position="left"
        class="user-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentUser.username" placeholder="请输入用户名" clearable :disabled="drawerMode === 'edit'" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="currentUser.nickname" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="currentUser.phone" placeholder="请输入手机号" clearable />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email" placeholder="请输入邮箱" clearable />
        </el-form-item>

        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="currentUser.roleIds" placeholder="请选择角色" multiple>
            <el-option v-for="role in userStore.rolesList" :key="role.roleId" :label="role.rolename"
              :value="role.roleId" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="isActive">
          <el-radio-group v-model="currentUser.isActive">
            <el-radio :value="true">已激活</el-radio>
            <el-radio :value="false">未激活</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" class="submit-btn">
            提交
          </el-button>
          <el-button @click="drawerVisible = false" class="cancel-btn">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { Search, Refresh, Plus, Edit, Delete, Iphone } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 使用Pinia store
const userStore = useUserStore()

// 搜索参数
const searchParams = ref({
  username: '',
  phone: '',
  email: '',
  roleIds: null,  // 改为复数形式，与后端一致
  isActive: null,
  nickname: ''
})

// 抽屉相关
const drawerVisible = ref(false)
const drawerMode = ref('add')
const currentUser = ref({
  username: '',
  phone: '',
  email: '',
  roleIds: [],  // 改为roleIds，与后端一致
  isActive: true,
  nickname: '',
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roleIds: [
    { required: false, message: '请选择角色', trigger: 'change' }
  ]
}

const userFormRef = ref(null)

// 角色显示格式化
// const formatRole = (roleName) => {
//   if (!roleName) return '未知角色'; // 处理无效输入
//   const roleMap = {

//     roleName
//   }
//   return roleMap[roleName] || '未知角色'
// }

// 角色标签类型
const getRoleTagType = (role) => {
  if (!role) return ''; // 处理无效输入
  const roleLower = role.toLowerCase();

  if (roleLower.includes('超级管理员')) {
    return 'danger';
  } else if (roleLower.includes('管理员')) {
    return 'warning';
  } else {
    return 'success';
  }
}
// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}
onMounted(() => {
  userStore.initData();
})
const drawerTitle = computed(() => {
  return drawerMode.value === 'add' ? '添加用户' : '编辑用户'
})
// 添加抽屉函数
const showAddDrawer = () => {
  drawerMode.value = 'add'
  currentUser.value = {
    username: '',
    phone: '',
    email: '',
    roleIds: [],
    isActive: true,
    // description: ''
  }
  drawerVisible.value = true
}

const handleEdit = (user) => {
  drawerMode.value = 'edit'
  // 将角色对象转换为角色ID数组
  const roleIds = user.roles.map(role => role.roleId)
  currentUser.value = {
    id: user.id,
    username: user.username,
    nickname: user.nickname || '',
    email: user.email,
    phone: user.phone,
    isActive: user.isActive,
    roleIds: roleIds
  }
  // 设置角色ID

  drawerVisible.value = true
}

// 禁用/启用用户
const toggleStatus = async (user) => {
  try {
    if (user.isActive) {
      // 当前是启用，点击后禁用
      await userStore.disableUser(user.id)
    } else {
      // 当前是禁用，点击后启用
      await userStore.enableUser(user.id)
    }
  } catch (e) {
    ElMessage.error(`操作失败: ${e.message || '未知错误'}`)
  }
}

const handleDelete = (user) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${user.username} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const result = await userStore.deleteUser(user.id)
    if (result) {
      userStore.fetchUsers()
    }
  }).catch(() => {
    // 取消删除
  })
}

// 新增/编辑用户
const submitForm = () => {
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      let result = false
      if (drawerMode.value === 'add') {
        // 调用新增用户
        result = await userStore.addUser(currentUser.value)
      } else {
        // 调用编辑用户
        // 编辑用户
        result = await userStore.editUser(currentUser.value.id, currentUser.value)
      }
      if (result) {
        drawerVisible.value = false
      }
    }
  })
}

// 搜索、重置、分页
const handleSearch = () => {
  userStore.page = 1
  userStore.searchUsers(searchParams.value)

}

const resetSearch = () => {
  searchParams.value = {
    username: '',
    phone: '',
    email: '',
    roleIds: null,
    isActive: null,
    nickname: ''
  }
  userStore.page = 1
  userStore.fetchUsers()
}

const handleSizeChange = (val) => {
  userStore.setPageSize(val)
}

const handleCurrentChange = (val) => {
  userStore.setPage(val)
}

// // 初始化获取用户列表
// onMounted(() => {
//   userStore.fetchUsers()
// })
</script>

<style scoped>
.user-management-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-area {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 12px;
}

.search-input {
  width: 240px;
}

.action-area {
  margin-bottom: 20px;
}

.table-area {
  flex: 1;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-form {
  padding: 0 20px;
}

/* 统一按钮样式 */
.search-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.reset-btn {
  color: #606266;
  border-color: #dcdfe6;
}

.add-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.submit-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.cancel-btn {
  color: #606266;
  border-color: #dcdfe6;
}

/* 状态按钮样式 */
:deep(.el-button--success.is-plain) {
  color: #67c23a;
  background-color: #f0f9eb;
  border-color: #c2e7b0;
}

:deep(.el-button--info.is-plain) {
  color: #909399;
  background-color: #f4f4f5;
  border-color: #d3d4d6;
}

:deep(.el-button--primary.is-plain) {
  color: #409eff;
  background-color: #ecf5ff;
  border-color: #b3d8ff;
}

:deep(.el-button--danger.is-plain) {
  color: #f56c6c;
  background-color: #fef0f0;
  border-color: #fbc4c4;
}

:deep(.el-drawer__header) {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

:deep(.el-drawer__body) {
  padding: 0;
}

:deep(.el-table .cell) {
  padding: 0 12px;
}

:deep(.el-table__header th) {
  background-color: #f8f8f9;
  font-weight: 600;
  color: #515a6e;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover>td) {
  background-color: #f5f7fa;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
  color: #fff;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #409eff;
}
</style>
